using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace Commons.Utils
{
	public class CollectionsHelper
	{
		public static IEnumerator SafeEnumerator(IEnumerator enumerator, Action<Exception> exceptionHandler = null)
		{
			while (SafeMoveNext(enumerator, exceptionHandler))
			{
				yield return enumerator.Current;
			}
		}

		public static bool SafeMoveNext(IEnumerator enumerator, Action<Exception> exceptionHandler = null)
		{
			try
			{
				return enumerator.MoveNext();
			}
			catch (Exception e)
			{
				if (exceptionHandler != null)
				{
					exceptionHandler(e);
				}
				else
				{
					Console.WriteLine(e);
				}

				return false;
			}
		}

		public static string ToString<K, V>(Dictionary<K, V> dictionary)
		{
			if (dictionary == null)
			{
				return "null";
			}

			StringBuilder s = new StringBuilder();

			foreach (KeyValuePair<K, V> pair in dictionary)
			{
				if (s.Length > 0)
				{
					s.Append(", ");
				}
				s.AppendFormat("{0}={1}", pair.Key, pair.Value);
			}

			s.Insert(0, '{').Append('}');

			return s.ToString();
		}

		public static string ToString<T>(IEnumerable<T> enumerable)
		{
			if (enumerable == null)
			{
				return "null";
			}

			StringBuilder s = new StringBuilder();

			foreach (T item in enumerable)
			{
				if (s.Length > 0)
				{
					s.Append(", ");
				}
				s.Append(item);
			}

			s.Insert(0, '[').Append(']');

			return s.ToString();
		}
	}
}

